import { Button, Input, message, Tabs, Modal, Select } from "antd"
import bgImg from "./assets/bg.jpg"
import { useEffect, useState } from "react";
import network from "./utils/network";
import Issued from "./components/issued/issued";
import { DeleteFilled } from "@ant-design/icons";
const { confirm } = Modal;

function App() {
  const [rulePlan, setRulePlan] = useState("");
  const [station, setStation] = useState("New001");
  const [activeKey, setActiveKey] = useState("");
  const [rulePlans, setRulePlans] = useState<any[]>([]);
  const AddCustRulePlanClick = async () => {
    if (!rulePlan) {
      message.warning("请填写方案的名字,不能为空");
      return;
    }
    setActiveKey(rulePlan)
    const lengthResult = await network(`http://127.0.0.1:5005/api/custRule/getRulesGroupByPlan/${rulePlan}`);
    if (lengthResult.data.result.length > 0) {
      setRulePlan("")
      message.warning("该方案已存在! 已切换方案 请添加规则");
      return;
    }
    const res = await network("http://127.0.0.1:5005/api/custRule/setRule", {
      rulePlan,
      ruleName: "",
      ruleContent: "",
      ruleLength: "",
      ruleUse: false
    }, "POST")
    if (res.data.code == 500) {
      message.warning(res.data.message);
      return;
    }
    GetData();
    message.success(rulePlan + "  方案添加成功了");
  }

  async function GetData() {
    const res = await network("http://127.0.0.1:5005/api/custRule/getRulesByPlan")
    setRulePlans(res.data.result)

    if (activeKey == "") {
      console.log("action");
      
      setActiveKey(res.data.result[0]?.rulePlan)
    }
  }
  useEffect(() => {
    GetData()
  }, []);
  const onChange = (key: string) => {
    setActiveKey(key)
  };
  const onEdit = async (targetKey: any, action: 'add' | 'remove') => {
    if (action === 'add') {
      // add();
    } else {
      // remove(targetKey);
      if(targetKey == "上线工位名称配方") {
        message.warning("默认配方,不能删除");
        return;
      }
      confirm({
        title: '删除配方选项',
        icon: <DeleteFilled />,
        content: <div>删除名称为: <span className="text-2xl font-bold text-green-400">{targetKey}</span> 的配方</div>,
        async onOk() {
          const res = await network("http://127.0.0.1:5005/api/custRule/by-plan?rulePlan=" + targetKey, {}, "DELETE")
          if (res.data.code == 500) {
            message.warning("更新失败!");
            return;
          }
          if (targetKey == activeKey) {
            setActiveKey(rulePlans[0].rulePlan)
          }
          message.warning("删除成功!");
          GetData();
        },
        onCancel() {
          message.info("取消删除!");
        },
        okText: '确认',
        cancelText: '取消',
      });

    }
  };
  const selectTable: any[] = [
    { value: 'New001', label: '1 工位 - 上线工位' },
    { value: 'New002', label: '2 工位 - 未命名' },
    { value: 'New003', label: '3 工位 - 未命名' },
    { value: 'New004', label: '4 工位 - 未命名' },
    { value: 'New005', label: '5 工位 - 未命名' },
    { value: 'New006', label: '6 工位 - 未命名' },
    { value: 'New007', label: '7 工位 - 未命名' },
  ]
  return (
    <div style={{
      backgroundImage: `url("${bgImg}")`,
      backgroundSize: "100%"
    }} className="h-full w-full px-12 py-8 flex bg-white/90 shadow-xl justify-center items-center ">
      <div className='flex flex-col h-full w-full bg-white/100 rounded-lg p-4 shadow-2xl'>
        <div className="flex gap-2 items-center">
          <span>方案名称:</span>
          <Input
            value={rulePlan}
            allowClear
            onChange={(v) => setRulePlan(v.currentTarget.value)}
            className="w-64!" placeholder="请输入新的规则方案名字" />
          <Button onClick={() => AddCustRulePlanClick()}
            type="primary">添加方案</Button>
          <span>下发位置:</span>
          <Select
            defaultValue={station}
            onChange={(key) => {
              setStation(key)
              console.log("key ", key);

            }} className={"w-96"} placeholder="请选择需要下发配方的工位" allowClear options={selectTable}></Select>
        </div>
        <div className="flex-1 mt-2 overflow-scroll">
          {rulePlans && <Tabs
            type="editable-card"
            onEdit={onEdit}
            hideAdd
            activeKey={activeKey}
            className="h-full" destroyOnHidden 
            items={rulePlans.map((item: any) => ({
              key: item.rulePlan,
              label: item.rulePlan,
              children: <Issued
                stationKey={station}
                Get={GetData} plan={item.rulePlan} />,
            }))} onChange={onChange} />}
        </div>
      </div>
    </div>
  )
}

export default App
